﻿using DBUtility;
using Jmit.Common;
using Jmit.Deyi.AutoTask;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace Jmit.Deyi.Job
{
    // 不允许此 Job 并发执行任务（禁止新开线程执行）
    // [DisallowConcurrentExecution]

    // DPS数据同步-DPS转储1天之前的数据（保留1天数据）
    public class DPSJob_dump : IJob
    {

        /// <summary>
        /// 定时任务：dps数据上传
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {
            return Task.Factory.StartNew(() =>
            {


                DUMP_dps_pick();





            });
        }


        /// <summary>
        /// dps_pick 表数据 （wms to dps）
        /// </summary>
        private void DUMP_dps_pick()
        {


            string sync_message = "";
            string sync_result = "";
            int sync_count = 0;
            

            string strCnn_wms = AppConfigManager.LoadConfig().dbConn_wms;
            string strCnn_dps = AppConfigManager.LoadConfig().dbConn_dps;

            try
            {

                LogHelpter.AddLog("DPS ==》BAK  数据备份 转储开始");

                //查询主档数据
                //string asyn_time = DateTime.Now.ToString("yyyy-MM-dd");

                string sql_dps = "";

                List<string> sqlList_dps = new List<string>();
                List<string> sqlList_wms = new List<string>();



                DateTime dt = DateTime.Now;
                string strYear = dt.Year.ToString();//2005


                // 检查目标表是否存在
                sql_dps = $" IF OBJECT_ID('dbo.dps_pick_" + strYear + "', 'U') IS NULL " +
                           " BEGIN "+
                           "   SELECT* INTO dbo.dps_pick_" + strYear + " FROM dbo.dps_pick WHERE 1 = 0; " +
                           " END ";

                sqlList_dps.Add(sql_dps);

                sql_dps = $" IF OBJECT_ID('dbo.dps_pickdtl_" + strYear + "', 'U') IS NULL " +
                           " BEGIN " +
                           "   SELECT * INTO dbo.dps_pickdtl_" + strYear + " FROM dbo.dps_pickdtl WHERE 1 = 0; " +
                           " END ";
                sqlList_dps.Add(sql_dps);
                OpDB.SaveDataToDB(strCnn_dps, sqlList_dps);


                // 备份数据
                sqlList_dps = new List<string>();

                sql_dps = $" INSERT  INTO dbo.dps_pick_" + strYear + " SELECT * FROM dbo.dps_pick    where   (convert(varchar(10),downtime,102) <= convert(varchar(10),getdate()-3,102) or  ( convert(varchar(10),uptime,102) = convert(varchar(10),getdate()-1,102) and dealflag='4') )     ";
                sqlList_dps.Add(sql_dps);

                sql_dps = $" DELETE FROM dbo.dps_pick                                                 where   (convert(varchar(10),downtime,102) <= convert(varchar(10),getdate()-3,102) or  ( convert(varchar(10),uptime,102) = convert(varchar(10),getdate()-1,102) and dealflag='4') )    ";
                sqlList_dps.Add(sql_dps);

                sql_dps = $" INSERT INTO dbo.dps_pickdtl_" + strYear + " SELECT * FROM dbo.dps_pickdtl where   (convert(varchar(10),downtime,102) <= convert(varchar(10),getdate()-3,102) or  ( convert(varchar(10),uptime,102) = convert(varchar(10),getdate()-1,102) and dealflag='4') )    ";
                sqlList_dps.Add(sql_dps);

                sql_dps = $" DELETE FROM dbo.dps_pickdtl                                               where   (convert(varchar(10),downtime,102) <= convert(varchar(10),getdate()-3,102) or  ( convert(varchar(10),uptime,102) = convert(varchar(10),getdate()-1,102) and dealflag='4') )     ";
                sqlList_dps.Add(sql_dps);

                // 上传到wms
                bool isok = OpDB.SaveDataToDB(strCnn_dps, sqlList_dps);
                if (isok)
                {
                    LogHelpter.AddLog("DPS ==》BAK  数据备份 转存成功");
                }
                else
                {

                    LogHelpter.AddLog("DPS ==》BAK  数据备份 转存失败");
                }

            }
            catch (Exception ex)
            {
                sync_message = "同步数据失败，错误消息=" + ex.Message;
                sync_result = "error";
                LogHelpter.AddLog(sync_message);
            }
        }

        /// <summary>
        /// dps_pickdtl 表数据 上传（dps to wms）
        /// </summary>
        private void UP_dps_pickdtl()
        {


            string sync_message = "";
            string sync_result = "";
            int sync_count = 0;
            // 定义每组的最大数量
            const int batchSize = 100;

            string strCnn_wms = AppConfigManager.LoadConfig().dbConn_wms;
            string strCnn_dps = AppConfigManager.LoadConfig().dbConn_dps;

            try
            {

                LogHelpter.AddLog("同步数据开始 [dps_pickdtl]  DPS ==》WMS 上传开始");

                //查询主档数据
                //string asyn_time = DateTime.Now.ToString("yyyy-MM-dd");

                string sql_dps = "";
                sql_dps = $" select * from dbo.dps_pickdtl where dealflag = 4 and upflag = 0 ";   // 同步每日数据


                int dataCount = 0;
                DataTable DT = OpDB.GetDataTable(strCnn_dps, sql_dps); 
                if (DT != null && DT.Rows.Count > 0)
                {
                    dataCount = DT.Rows.Count;
                    // 全部执行
                    List<DataRow> currentBatch = new List<DataRow>();
                    foreach (DataRow row in DT.Rows)
                    {
                        currentBatch.Add(row);
                    }
                    bool isok = batchSql_dps_pick_up(currentBatch);

                    // 分批执行

                    //// 临时存储当前批次的数据
                    //List<DataRow> currentBatch = new List<DataRow>();
                    //foreach (DataRow row in DT.Rows)
                    //{
                    //    currentBatch.Add(row);

                    //    // 如果当前批次达到最大数量，将其添加到分组列表中，并重置当前批次
                    //    if (currentBatch.Count == batchSize)
                    //    {
                    //        batchSql_dps_pick(currentBatch);
                    //        currentBatch = new List<DataRow>();
                    //    }
                    //}


                    //// 如果还有剩余的数据，将其添加到分组列表中
                    //if (currentBatch.Count > 0)
                    //{
                    //    batchSql_dps_pick(currentBatch);
                    //    currentBatch = new List<DataRow>();
                    //}

                }

                LogHelpter.AddLog("DPS ==》WMS [dps_pickdtl]上传成功，数量：" + dataCount);


            }
            catch (Exception ex)
            {
                sync_message = "同步数据失败，错误消息=" + ex.Message;
                sync_result = "error";
                LogHelpter.AddLog(sync_message);
            }
        }

        private static bool batchSql_dps_pick_up(List<DataRow> currentBatch)
        {
            LogHelpter.AddLog("行数：" + currentBatch.Count);

            string strCnn_wms = AppConfigManager.LoadConfig().dbConn_wms;
            string strCnn_dps = AppConfigManager.LoadConfig().dbConn_dps;

            List<string> sqlList_dps = new List<string>();
            List<string> sqlList_wms = new List<string>();


            foreach (DataRow row in currentBatch)
            {

                string billno = String2Json(row["billno"].ToString().Trim());
                string positioncode = String2Json(row["positioncode"].ToString().Trim());
                string shopcode = String2Json(row["shopcode"].ToString().Trim());
                string turnoverboxcode = String2Json(row["turnoverboxcode"].ToString()); // 周转箱号
                string shouldamount = String2Json(row["shouldamount"].ToString()); // 应拣货数量
                string actualamount = String2Json(row["actualamount"].ToString()); // 实际拣货数量
                string picker = String2Json(row["picker"].ToString());                  // 拣货人
                string actualboxcode = String2Json(row["actualboxcode"].ToString());    // 实际箱号



                string sql_wms = $" update wms.dps_pickdtl set actualamount= '{actualamount}',picker= '{picker}',actualboxcode= '{actualboxcode}', uptime=GETDATE(),upflag=1, dealflag = 4  where billno = '{billno}' and positioncode = '{positioncode}'  and upflag=0 ";
                sqlList_wms.Add(sql_wms);

                string sql_dps = $" update dbo.dps_pickdtl set uptime=GETDATE(),upflag=1 where billno = '{billno}' and positioncode = '{positioncode}'  and upflag=0 ";
                sqlList_dps.Add(sql_dps);



            }

            // 上传到wms
            bool isok = OpDB.SaveDataToDB(strCnn_wms, sqlList_wms);// 更新wms状态
            if (isok)
            {
                OpDB.SaveDataToDB(strCnn_dps, sqlList_dps); 
            }
            else
            {
                LogHelpter.AddLog("[dps_pickdtl] 上传失败,数量：" + currentBatch.Count);
            }
            return isok;
        }


        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>json字符串</returns>
        private static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\'':
                        sb.Append("\\\'"); break;
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }

    }
}
